import { MockMethod } from "vite-plugin-mock";
import { ApiMethod, ApiStatus, ApiType } from "@/types/api";

// Mock API列表
const mockApis = [
  {
    id: 1,
    name: "用户查询",
    path: "/api/users",
    method: ApiMethod.GET,
    type: ApiType.DataSource,
    status: ApiStatus.Enabled,
    description: "查询用户列表",
    dataSourceId: 1,
    config: {
      sql: "SELECT * FROM users WHERE status = :status",
      params: {
        status: { type: "number", defaultValue: 1 },
      },
      cache: {
        enabled: true,
        timeout: 60000,
      },
      page: {
        enabled: true,
        pageSize: 20,
      },
    },
    requestSchema: JSON.stringify(
      {
        type: "object",
        properties: {
          status: { type: "number" },
        },
      },
      null,
      2
    ),
    responseSchema: JSON.stringify(
      {
        type: "object",
        properties: {
          id: { type: "number" },
          username: { type: "string" },
          email: { type: "string" },
        },
      },
      null,
      2
    ),
    createdAt: "2023-06-01 12:00:00",
    updatedAt: "2023-06-01 12:00:00",
  },
  {
    id: 2,
    name: "天气查询",
    path: "/api/weather",
    method: ApiMethod.GET,
    type: ApiType.REST,
    status: ApiStatus.Enabled,
    description: "查询城市天气",
    config: {
      url: "https://api.example.com/weather",
      method: "GET",
      headers: {
        "Content-Type": "application/json",
      },
    },
    requestSchema: JSON.stringify(
      {
        type: "object",
        properties: {
          city: { type: "string" },
        },
        required: ["city"],
      },
      null,
      2
    ),
    responseSchema: JSON.stringify(
      {
        type: "object",
        properties: {
          temperature: { type: "number" },
          humidity: { type: "number" },
          description: { type: "string" },
        },
      },
      null,
      2
    ),
    createdAt: "2023-06-02 09:30:00",
    updatedAt: "2023-06-02 09:30:00",
  },
];

// 延迟函数
const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

export default [
  // 获取API列表
  {
    url: "/admin-api/api/list",
    method: "get",
    response: async (req: any) => {
      await delay(500);
      const { keyword, page = 1, pageSize = 10 } = req.query;

      let filtered = [...mockApis];

      // 如果有关键字，进行过滤
      if (keyword) {
        filtered = filtered.filter(
          (item) =>
            item.name.toLowerCase().includes(keyword.toLowerCase()) ||
            item.path.toLowerCase().includes(keyword.toLowerCase())
        );
      }

      // 分页
      const start = (page - 1) * pageSize;
      const end = start + pageSize;
      const paged = filtered.slice(start, end);

      return {
        code: 0,
        message: "成功",
        data: {
          list: paged,
          total: filtered.length,
        },
      };
    },
  },

  // 创建API
  {
    url: "/admin-api/api/create",
    method: "post",
    response: async (req: any) => {
      await delay(500);
      const newApi = {
        ...req.body,
        id: mockApis.length + 1,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
      };

      mockApis.push(newApi);

      return {
        code: 0,
        message: "创建成功",
        data: newApi,
      };
    },
  },

  // 更新API
  {
    url: "/admin-api/api/update",
    method: "put",
    response: async (req: any) => {
      await delay(500);
      const { id } = req.query;
      const index = mockApis.findIndex((item) => item.id === Number(id));

      if (index === -1) {
        return {
          code: 404,
          message: "API不存在",
          data: null,
        };
      }

      mockApis[index] = {
        ...mockApis[index],
        ...req.body,
        updatedAt: new Date().toISOString(),
      };

      return {
        code: 0,
        message: "更新成功",
        data: mockApis[index],
      };
    },
  },

  // 删除API
  {
    url: "/admin-api/api/delete",
    method: "delete",
    response: async (req: any) => {
      await delay(500);
      const { id } = req.query;
      const index = mockApis.findIndex((item) => item.id === Number(id));

      if (index === -1) {
        return {
          code: 404,
          message: "API不存在",
          data: null,
        };
      }

      mockApis.splice(index, 1);

      return {
        code: 0,
        message: "删除成功",
        data: null,
      };
    },
  },

  // 测试API
  {
    url: "/admin-api/api/test",
    method: "post",
    response: async (req: any) => {
      await delay(1000);
      const { id } = req.query;
      const api = mockApis.find((item) => item.id === Number(id));

      if (!api) {
        return {
          code: 404,
          message: "API不存在",
          data: {
            success: false,
            message: "API不存在",
          },
        };
      }

      // 根据API类型返回不同的测试结果
      let result;
      if (api.type === ApiType.DataSource) {
        result = {
          success: true,
          message: "SQL执行成功",
          data: {
            sql: api.config.sql,
            params: api.config.params,
            result: [
              { id: 1, username: "user1", email: "user1@example.com" },
              { id: 2, username: "user2", email: "user2@example.com" },
            ],
          },
        };
      } else {
        result = {
          success: true,
          message: "REST接口调用成功",
          data: {
            url: api.config.url,
            method: api.config.method,
            result: {
              temperature: 25,
              humidity: 60,
              description: "晴朗",
            },
          },
        };
      }

      return {
        code: 0,
        message: "测试成功",
        data: result,
      };
    },
  },
] as MockMethod[];
